<template>
  <div class = 'container'>
    <el-card class = "box-card">
      <el-row :gutter = "20">
        <el-form ref = "form" label-width = "80px">
          <el-col :span = "5">
            <div class = "grid-content bg-purple">
              <el-form-item label = "关键字">
                <el-input v-model = "queryParameter.keyword" placeholder = "请根据文章标题搜索"></el-input>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span = "5">
            <div class = "grid-content bg-purple">
              <el-form-item label = "状态">
                <el-select v-model = "queryParameter.state" placeholder = "请选择">
                  <el-option label = "已启用" value = "1"></el-option>
                  <el-option label = "已禁用" value = "0"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-col>
        </el-form>
        <el-col :span = "4">
          <div class = "grid-content bg-purple">
            <el-button @click = "clearSearchResults">清除</el-button>
            <el-button @click = "getArticleList" type = "primary">搜索</el-button>
          </div>
        </el-col>
        <el-col :offset = "7" :span = "2">
          <div class = "grid-content bg-purple">
            <el-button icon = "el-icon-edit" type = "success" @click = "addDialogVisible=true">新建技巧</el-button>
          </div>
        </el-col>
      </el-row>
      <template>
        <el-alert style = "margin-bottom: 10px" :title = "`数据一共 ${counts} 条`" type = "info" show-icon
                  :closable = "false"></el-alert>
      </template>
      <div>
        <template>
          <el-table ref = "singleTable" :data = "items" highlight-current-row center>
            <el-table-column align="center" type = "index" label = "序号" width = "100px"></el-table-column>
            <el-table-column align="center" label = "文章标题" width = "350px">
              <template slot-scope = "scope">
                {{ scope.row.title }}
                <!--                视频-->
                <i @click = "videoDialogVisible=true;videoUrl=scope.row.videoURL" style = "color: #409eff"
                   class = "el-icon-video-play" v-if = "scope.row.videoURL ? scope.row.videoURL.trim() :false" />
              </template>
            </el-table-column>
            <el-table-column align="center" prop = "visits" label = "阅读数" width = "100px"></el-table-column>
            <el-table-column align="center" prop = "username" label = "导入人" width = "150px"></el-table-column>
            <el-table-column align="center" prop = "createTime" label = "导入时间" width = "200px"></el-table-column>
            <el-table-column align="center" prop = "state" label = "状态" width = "100px">
              <template slot-scope = "scope">
                <el-tag type = "success" v-if = "scope.row.state">已启用</el-tag>
                <el-tag type = "danger" v-else>已禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label = "操作">
              <template slot-scope = "scope">
                <el-button size = "mini" type = "success"
                           @click = "previewDialogVisible = true;articleDetails = scope.row">预览
                </el-button>
                <el-button size = "mini" type = "danger" v-if = "scope.row.state"
                           @click = "articleStateChange(scope.row)">禁用
                </el-button>
                <el-button size = "mini" type = "success" v-else @click = "articleStateChange(scope.row)">启用</el-button>
                <el-button size = "mini" type = "warning" disabled v-if = "scope.row.state">修改</el-button>
                <el-button size = "mini" type = "warning" v-else
                           @click = "editDialogVisible = true;editArticleParameter=scope.row">修改
                </el-button>
                <el-button size = "mini" type = "danger" disabled v-if = "scope.row.state">删除</el-button>
                <el-button size = "mini" type = "danger" v-else @click = "delArticle(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div class = "block" style = "margin:20px;float: right">
        <el-pagination
          background
          @size-change = "handleSizeChange"
          @current-change = "handleCurrentChange"
          :current-page = "queryParameter.page"
          :page-sizes = "[5, 10, 20, 50]"
          :page-size = "queryParameter.pagesize"
          layout = "prev, pager, next,sizes,jumper"
          :total = "counts">
        </el-pagination>
      </div>
    </el-card>
    <!--    视频对话框-->
    <el-dialog
      class="player"
      title="视频"
      :visible.sync = "videoDialogVisible"
      width = "640px">
      <div class = "video-box">
        <video autoplay :src = "videoUrl"></video>
      </div>
    </el-dialog>
    <!--    文章预览对话框-->
    <el-dialog
      title = "预览文章"
      :visible.sync = "previewDialogVisible"
      width = "50%">
      <articles-preview :ArticleDetails = "articleDetails"></articles-preview>
    </el-dialog>
    <!--    新增文章对话框-->
    <el-dialog
      title = "提示"
      :visible.sync = "addDialogVisible"
      width = "50%">
      <articles-add @onArticleParameter = "getArticleParameter" :article-rules="articleRules"></articles-add>
      <span slot = "footer" class = "dialog-footer">
        <el-button @click = "addDialogVisible = false">取 消</el-button>
        <el-button type = "primary" @click = "addArticle">确 定</el-button>
      </span>
    </el-dialog>
    <!--    修改文章对话框-->
    <el-dialog
      title = "修改文章"
      :visible.sync = "editDialogVisible"
      width = "50%">
      <el-form :model = "editArticleParameter" :rules="articleRules" label-width = "100px">
        <el-form-item label = "文章标题：" prop = "title">
          <el-input v-model = "editArticleParameter.title" placeholder = "请输入文章标题"></el-input>
        </el-form-item>
        <el-form-item label = "文章内容：" prop = "articleBody">
          <quill-editor v-model = "editArticleParameter.articleBody" class = "myQuillEditor"
                        :options = "editorOption" />
        </el-form-item>
        <el-form-item label = "视频地址：" prop = "videoURL">
          <el-input v-model = "editArticleParameter.videoURL" placeholder = "请输入视频地址"></el-input>
        </el-form-item>
      </el-form>
      <span slot = "footer" class = "dialog-footer">
        <el-button @click = "editDialogVisible = false">取 消</el-button>
        <el-button type = "primary" @click = "editArticle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as Article from '@/api/hmmm/articles'
import ArticlesPreview from '@/module-hmmm/components/articles-preview'
import ArticlesAdd from '@/module-hmmm/components/articles-add'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import dayjs from 'dayjs'

export default {
  name: 'Articles',
  data () {
    return {
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ]
        },
        placeholder: ''
      },
      select1: '',
      ArticleList: [],
      // 请求参数
      queryParameter: {
        page: 1,
        pagesize: 10,
        keyword: '',
        state: null
      },
      items: [], // 文章列表数据
      counts: null, // 文章数
      videoUrl: null, // 视频地址
      videoDialogVisible: false, // 视频对话框默认隐藏
      previewDialogVisible: false, // 预览文章对话框默认隐藏
      articleDetails: null, // 文章详情
      addDialogVisible: false, // 新增文章对话框默认隐藏
      articleParameter: {}, // 新增文章详情
      editDialogVisible: false, // 修改文章对话框默认隐藏
      // 修改文章参数
      editArticleParameter: {
        id: '',
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 文章校验规则
      articleRules: {
        title: [{
          required: true,
          message: '请输入文章标题',
          trigger: 'blur'
        }],
        articleBody: [{
          required: true,
          message: '请输入文章内容',
          trigger: 'blur'
        }]
      }
    }
  },
  components: {
    ArticlesPreview,
    ArticlesAdd,
    quillEditor
  },
  created () {
    this.getArticleList()
  },
  methods: {
    // 获取文章列表
    async getArticleList () {
      try {
        const { data: res } = await Article.list(this.queryParameter)
        res.items.forEach(item => {
          item.createTime = dayjs(item.createTime).format('YYYY-MM-DD hh:mm:ss')
        })
        console.log('文章列表', res)
        this.items = res.items
        this.counts = res.counts
      } catch (err) {
        console.log(err)
      }
    },
    // 分页
    handleSizeChange (pagesize) {
      this.queryParameter.pagesize = pagesize
      this.getArticleList()
    },
    handleCurrentChange (page) {
      this.queryParameter.page = page
      this.getArticleList()
    },
    // 清除搜索结果
    async clearSearchResults () {
      this.queryParameter.keyword = ''
      this.queryParameter.state = null
      await this.getArticleList()
    },
    // 改变文章状态
    async articleStateChange (row) {
      try {
        await Article.changeState({ id: row.id, state: row.state === 1 ? 0 : 1 })
        this.$message.success('操作成功')
        row.state = row.state === 1 ? 0 : 1
        await this.getArticleList()
      } catch (err) {
        this.$message.error('请求错误')
        console.log(this.id, this.state)
        console.log(row)
      }
    },
    // 从子组件获取文章数据
    getArticleParameter (articleParameter) {
      this.articleParameter = articleParameter
    },
    // 添加文章
    async addArticle () {
      try {
        await Article.add(this.articleParameter)
        this.$message.success('添加成功')
        this.addDialogVisible = false
        await this.getArticleList()
      } catch (err) {
        this.$message.error('添加失败')
      }
    },
    // 修改文章
    async editArticle () {
      try {
        await Article.update(this.editArticleParameter)
        this.$message.success('修改成功')
        this.editDialogVisible = false
        await this.getArticleList()
      } catch (err) {
        this.$message.error('修改失败')
      }
    },
    // 删除文章
    delArticle (row) {
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await Article.remove(row)
        console.log(row.id)
        console.log(res)
        if (!res.success) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        await this.getArticleList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style scoped lang = 'scss'>
::v-deep .ql-editor {
  min-height: 200px !important;
}
.player{
  ::v-deep .el-dialog__body{
    padding: 0;
  }
}
.video-box{
  width: 640px;
  height:360px;
  video{
    width: 640px!important;
    overflow: hidden;
  }
}
</style>
